package com.snow.useviewdemo.play;

import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

/**
 * Created by zhaoyingtao
 * Date: 2020/7/16
 * Describe:
 */
public class FloatViewMoveListener implements View.OnTouchListener {

    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private int mTouchStartX;
    private int mTouchStartY;
    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private int mStartX, mStartY;
    //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    private boolean isMove;
    WindowManager mWindowManager;
    View mShowView;
    WindowManager.LayoutParams mFloatParams;

    public FloatViewMoveListener(WindowManager mWindowManager, View mShowView, WindowManager.LayoutParams mFloatParams) {
        this.mWindowManager = mWindowManager;
        this.mShowView = mShowView;
        this.mFloatParams = mFloatParams;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (mFloatParams == null || mShowView == null || mWindowManager == null) {
            return isMove;
        }
        int action = motionEvent.getAction();
        int x = (int) motionEvent.getX();
        int y = (int) motionEvent.getY();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isMove = false;
                mTouchStartX = (int) motionEvent.getRawX();
                mTouchStartY = (int) motionEvent.getRawY();
                mStartX = x;
                mStartY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                int mTouchCurrentX = (int) motionEvent.getRawX();
                int mTouchCurrentY = (int) motionEvent.getRawY();
                mFloatParams.x += mTouchCurrentX - mTouchStartX;
                mFloatParams.y += mTouchCurrentY - mTouchStartY;
                mWindowManager.updateViewLayout(mShowView, mFloatParams);
                mTouchStartX = mTouchCurrentX;
                mTouchStartY = mTouchCurrentY;
                float deltaX = x - mStartX;
                float deltaY = y - mStartY;
                if (Math.abs(deltaX) >= 5 || Math.abs(deltaY) >= 5) {
                    isMove = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                break;
        }
        //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
        return isMove;
    }
}
